import styles from './index.module.scss'
import Dialog from '@c/dialog'
import cm from 'classnames'
import { useRef, useEffect, useMemo, useState } from 'react'
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'
import Copy from 'clipboard'
import message from '@c/message'
import { userInfo } from '@/store'
import { useRecoilValue } from 'recoil'
import { taskFinished } from '@/api/score'
import { activeClickReport } from '@/utils/report'
import { devicePlatform } from '@/utils/utils'
import domtoimage from 'dom-to-image-more'
import Loading from '@c/request-loading'

const Index = props => {
  const { onClose, code } = props
  const refQrcode = useRef(null)
  const refPoster = useRef(null)
  const [ios, setIOS] = useState(false)
  const user = useRecoilValue(userInfo)
  const [loading, setLoading] = useState(true)
  const shareUrl = useMemo(() => {
    const isTest = process.env.NEXT_PUBLIC_BAN_CONSOLE != '1'
    const url = `https://${isTest ? 'web' : 'www'}.histar.tv/invited?invite_code=${code || user.id || '0'}`
    return url
  }, [user])

  useEffect(() => {
    const img1 = new Image()
    img1.src = '/images/poster.png'
    const { isIOS } = devicePlatform()
    setIOS(isIOS)
    QRCode.toDataURL(shareUrl, { margin: 0 }, (err, url) => {
      if (err) throw err
      refQrcode.current.src = url
      const img2 = new Image()
      img1.onload = () => {
        img2.src = url
      }
      img2.onload = async () => {
        const scale = window.devicePixelRatio
        const width = refPoster.current.offsetWidth
        const height = refPoster.current.offsetHeight
        const dataUrl = await domtoimage.toPng(refPoster.current, {
          quality: 1,
          style: {
            transform: 'scale(' + scale + ')',
            transformOrigin: 'top left',
            width: width + 'px',
            height: height + 'px'
          },
          width: width * scale,
          height: height * scale
        })
        document.querySelector('#iosImg').src = dataUrl
        domtoimage
          .toPng(refPoster.current, {
            quality: 1,
            style: {
              transform: 'scale(' + scale + ')',
              transformOrigin: 'top left',
              width: width + 'px',
              height: height + 'px'
            },
            width: width * scale,
            height: height * scale
          })
          .then(res => {
            setLoading(false)
            document.querySelector('#iosImg').src = res
          })
      }
    })

    const copyUrl = new Copy('.btn')
    copyUrl.on('success', () => {
      message({ content: '分享信息复制成功，发给朋友一起看吧！' })
      taskFinished({
        completionStatus: 4,
        ydtoken: ''
      })
    })
  }, [])

  const save = () => {
    activeClickReport({
      share_status: '分享海报'
    })
    html2canvas(refPoster.current, { scale: 5 }).then(canvas => {
      canvas.toBlob(blob => {
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '分享海报.png'
        link.click()
        setTimeout(() => {
          taskFinished({
            completionStatus: 4,
            ydtoken: ''
          })
          window.URL.revokeObjectURL(url)
        }, 0)
      })
    })
  }

  const toCopy = () => {
    activeClickReport({
      share_status: '分享链接'
    })
  }

  const imgStyle = useMemo(() => {
    if (!refPoster.current) {
      return {}
    }
    return {
      width: refPoster.current.offsetWidth,
      height: refPoster.current.offsetHeight
    }
  }, [refPoster])

  return (
    <>
      <Dialog className={cm(styles.content)}>
        <div className={styles.posterBody} ref={refPoster}>
          <img src="/images/poster.png" alt="" className={styles.img} />
          <img ref={refQrcode} className={styles.qrcode} alt="" />
        </div>
        {loading && <Loading className="absolute left-0 top-0 z-4" />}
        <img
          className={cm(styles.posterBodyImg, ios ? 'block' : 'hidden')}
          id="iosImg"
          rc="/images/poster.png"
          style={imgStyle}
          alt=""
        />
        <div className={styles.close} onClick={onClose}>
          取消
        </div>
        <div className={styles.btnGroup}>
          {ios ? (
            <div className={cm(styles.btn)}>长按图片保存</div>
          ) : (
            <div className={cm(styles.btn)} onClick={save}>
              保存海报
            </div>
          )}
          <div
            className={cm(styles.btn, 'btn')}
            data-clipboard-text={`送你星视界会员，免费看全网影视，点链接领：${shareUrl}`}
            onClick={toCopy}
          >
            复制链接
          </div>
        </div>
      </Dialog>
    </>
  )
}

export default Index
